package com.zlsy.thread.threadlocal;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.format.datetime.standard.DateTimeContextHolder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhouliang
 * @date 2020/7/14 19:38
 */
public class ThreadLocalNPE {
    ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    public Long get() {
        return threadLocal.get();
    }

    /**
     * 空指针问题，如果还没set就get的话，那么由于还没初始化的initialValue返回为null
     * 用一个long去接null，装箱拆箱报错
     * @return
     */
    public long badGet() {
        return threadLocal.get();
    }

    public void set() {
        threadLocal.set(Thread.currentThread().getId());
    }

    public static void main(String[] args) {
        ThreadLocalNPE threadLocalNPE = new ThreadLocalNPE();
        //主线程get
        System.out.println(threadLocalNPE.get());

        //子线程set
        ExecutorService executorService = Executors.newSingleThreadExecutor(
                new BasicThreadFactory
                        .Builder()
                        .namingPattern("thread-local-npe-test-%s-")
                        .build());
        executorService.execute(threadLocalNPE::get);
        executorService.shutdown();
    }
}
